﻿using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;

namespace Admin.NET.Application;

/// <summary>
/// 模板预警服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class DeiviceTemplateTriggerService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<DeiviceTemplateTrigger> _deiviceTemplateTriggerRep;

    public DeiviceTemplateTriggerService(SqlSugarRepository<DeiviceTemplateTrigger> deiviceTemplateTriggerRep)
    {
        _deiviceTemplateTriggerRep = deiviceTemplateTriggerRep;
    }

    /// <summary>
    /// 分页查询模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询模板预警")]
    public async Task<SqlSugarPagedList<DeiviceTemplateTriggerOutput>> Page(PageDeiviceTemplateTriggerInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _deiviceTemplateTriggerRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.TriggerName.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.TriggerName), u => u.TriggerName.Contains(input.TriggerName.Trim()))
            .WhereIF(input.TemplatePointId > 0, u => u.TemplatePointId == input.TemplatePointId)
            .WhereIF(input.CreateOrgId > 0, u => u.CreateOrgId == input.CreateOrgId)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<DeviceSlaveTemplatePoints>((u, templatepointid) => u.TemplatePointId == templatepointid.Id)
            .LeftJoin<DeviceSlaveTemplatePoints>((u, templatepointid, controltemplatepointid) => u.ControlTemplatePointId == controltemplatepointid.Id)
            .Select((u, templatepointid, controltemplatepointid) => new DeiviceTemplateTriggerOutput
            {
                Id = u.Id,
                TriggerName = u.TriggerName,
                TriggerType = u.TriggerType,
                TemplatePointId = u.TemplatePointId,
                TemplatePointIdPointName = templatepointid.PointName,
                TriggerCondition = u.TriggerCondition,
                Status = u.Status,
                Capture = u.Capture,
                CustomContentAlarm = u.CustomContentAlarm,
                CustomContentNormal = u.CustomContentNormal,
                LinkageControlStatus = u.LinkageControlStatus,
                Remark = u.Remark,
                ControlType = u.ControlType,
                LinkageControlSendType = u.LinkageControlSendType,
                ControlTemplatePointId = u.ControlTemplatePointId,
                ControlTemplatePointIdPointName = controltemplatepointid.PointName,
                ControlSendData = u.ControlSendData,
                Max = u.Max,
                Min = u.Min,
                DeadZone = u.DeadZone,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加模板预警")]
    public async Task<long> Add(AddDeiviceTemplateTriggerInput input)
    {
        var entity = input.Adapt<DeiviceTemplateTrigger>();
        await _deiviceTemplateTriggerRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除模板预警")]
    public async Task Delete(DeleteDeiviceTemplateTriggerInput input)
    {
        var entity = await _deiviceTemplateTriggerRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deiviceTemplateTriggerRep.FakeDeleteAsync(entity);   //假删除
        //await _deiviceTemplateTriggerRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新模板预警")]
    public async Task Update(UpdateDeiviceTemplateTriggerInput input)
    {
        var entity = input.Adapt<DeiviceTemplateTrigger>();
        await _deiviceTemplateTriggerRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取模板预警")]
    public async Task<DeiviceTemplateTrigger> Detail([FromQuery] QueryByIdDeiviceTemplateTriggerInput input)
    {
        return await _deiviceTemplateTriggerRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 通过变量获取模板预警
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "DetailByPointId")]
    [DisplayName("通过变量获取模板预警")]
    public async Task<DeiviceTemplateTriggerOutput> DetailByPointId([FromQuery] QueryByIdDeiviceTemplateTriggerInput input)
    {
        var ouput = await _deiviceTemplateTriggerRep.AsQueryable().Where(u => u.TemplatePointId == input.Id)
             //处理外键和TreeSelector相关字段的连接
             .LeftJoin<DeviceSlaveTemplatePoints>((u, templatepointid) => u.TemplatePointId == templatepointid.Id)
              .LeftJoin<DeviceSlaveTemplatePoints>((u, templatepointid, controltemplatepointid) => u.ControlTemplatePointId == controltemplatepointid.Id).Select((u, templatepointid, controltemplatepointid) => new DeiviceTemplateTriggerOutput
              {
                  Id = u.Id,
                  TriggerName = u.TriggerName,
                  TriggerType = u.TriggerType,
                  TemplatePointId = u.TemplatePointId,
                  TemplatePointIdPointName = templatepointid.PointName,
                  TriggerCondition = u.TriggerCondition,
                  Status = u.Status,
                  Capture = u.Capture,
                  CustomContentAlarm = u.CustomContentAlarm,
                  CustomContentNormal = u.CustomContentNormal,
                  LinkageControlStatus = u.LinkageControlStatus,
                  Remark = u.Remark,
                  ControlType = u.ControlType,
                  LinkageControlSendType = u.LinkageControlSendType,
                  ControlTemplatePointId = u.ControlTemplatePointId,
                  ControlTemplatePointIdPointName = controltemplatepointid.PointName,
                  ControlSendData = u.ControlSendData,
                  Max = u.Max,
                  Min = u.Min,
                  DeadZone = u.DeadZone,
                  CreateOrgId = u.CreateOrgId,
                  CreateOrgName = u.CreateOrgName,
                  CreateTime = u.CreateTime,
                  UpdateTime = u.UpdateTime,
                  CreateUserId = u.CreateUserId,
                  CreateUserName = u.CreateUserName,
                  UpdateUserId = u.UpdateUserId,
                  UpdateUserName = u.UpdateUserName,
                  IsDelete = u.IsDelete,
              }).FirstAsync();
        return ouput;
    }

    /// <summary>
    /// 获取模板预警列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取模板预警列表")]
    public async Task<List<DeiviceTemplateTriggerOutput>> List([FromQuery] PageDeiviceTemplateTriggerInput input)
    {
        return await _deiviceTemplateTriggerRep.AsQueryable().Select<DeiviceTemplateTriggerOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取从机变量列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceSlaveTemplatePointsTemplatePointIdDropdown"), HttpGet]
    [DisplayName("获取从机变量列表")]
    public async Task<dynamic> DeviceSlaveTemplatePointsTemplatePointIdDropdown()
    {
        return await _deiviceTemplateTriggerRep.Context.Queryable<DeviceSlaveTemplatePoints>()
                .Select(u => new
                {
                    Label = u.PointName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取联动的变量列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceSlaveTemplatePointsControlTemplatePointIdDropdown"), HttpGet]
    [DisplayName("获取联动的变量列表")]
    public async Task<dynamic> DeviceSlaveTemplatePointsControlTemplatePointIdDropdown()
    {
        return await _deiviceTemplateTriggerRep.Context.Queryable<DeviceSlaveTemplatePoints>()
                .Select(u => new
                {
                    Label = u.PointName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
}